package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author atguigu-mqx
 */
@Service
public class ManageServiceImpl implements ManageService {
    //  需要调用mapper层
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuPosterMapper spuPosterMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private RabbitService rabbitService;



    @Override
    public List<BaseCategory1> getCategory1() {
        //  select * from base_category1;
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        //  select * from base_category2 where category1_id = category1Id;
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id", category1Id));
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        //  select * from base_category3 where category2_id = category2Id

        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id", category2Id));
    }

    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        /*
        select *
        from base_attr_info bai
                 inner join base_attr_value bav
                            on bai.id = bav.attr_id
        where (category_id = ? and category_level = 1)
           or (category_id = ? and category_level = 2)
           or (category_id = ? and category_level = 3);
         可以使用Mapper.xml 配置文件！
         */
        return baseAttrInfoMapper.selectAttrInfoList(category1Id, category2Id, category3Id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //  baseAttrInfo 平台属性表！
        if (baseAttrInfo.getId() != null) {
            //  修改  update baseAttrInfo set baseName = ? where id = ?;
            baseAttrInfoMapper.updateById(baseAttrInfo);

        } else {
            //  baseAttrInfo!   一开始页面传递的时候 id = null ，经过insert 之后 @TableId(type = IdType.AUTO) 自动获取到生产主键Id
            baseAttrInfoMapper.insert(baseAttrInfo);
        }
        //  int i=1/0;
        //  baseAttrValue   如何修改！   先删除，再新增！ 逻辑删除！
        QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id", baseAttrInfo.getId()); // 因为insert 在前面执行，@TableId(type = IdType.AUTO)
        baseAttrValueMapper.delete(queryWrapper);

        //  获取到平台属性值数据！
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //  判断当前集合是否为空！
        if (!CollectionUtils.isEmpty(attrValueList)) {
            //  循环遍历
            for (BaseAttrValue baseAttrValue : attrValueList) {
                //  attrId = baseAttrInfo.getId(); 前端页面提交attrId 为null ，所以在此处需要将attrId 赋值！
                baseAttrValue.setAttrId(baseAttrInfo.getId()); // @TableId(type = IdType.AUTO)
                //  循环执行insert into 语句！
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }
    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        //  select * from baseAttreValue where attr_Id = attrId;
        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId));
    }

    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        //   select * from baseAttrInfo where id = 1;
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        //  方法整合
        if (baseAttrInfo != null) {
            baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        }
        //  返回数据！
        return baseAttrInfo;
    }

    @Override
    public IPage getSpuInfoList(Page<SpuInfo> spuInfoPage, SpuInfo spuInfo) {
        //  select * from spu_info where category3_id = ? order by id desc limit 1 , 10 ;
        //  Page 类
        //  构建查询条件
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id", spuInfo.getCategory3Id());
        spuInfoQueryWrapper.orderByDesc("id");
        return spuInfoMapper.selectPage(spuInfoPage, spuInfoQueryWrapper);
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        //        spu_info
        //        spu_poster
        //        spu_sale_attr
        //        spu_sale_attr_value
        //        spu_image
        //  插入spuInfo
        spuInfoMapper.insert(spuInfo);


        //  获取商品的图片列表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)) {
            spuImageList.forEach(spuImage -> {
                //  细节：
                spuImage.setSpuId(spuInfo.getId()); //  因为insert 在上面！
                spuImageMapper.insert(spuImage);
            });
        }

        //  spu_poster
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)) {
            spuPosterList.forEach(spuPoster -> {
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            });
        }

        //  spu_sale_attr
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            spuSaleAttrList.forEach(spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                //  spu_sale_attr_value
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            });
        }
    }

    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        //  多表关联查询！
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        /*
        sku_attr_value
        sku_image
        sku_info
        sku_sale_attr_value
         */
        //  sku_info
        skuInfoMapper.insert(skuInfo);
        //  sku_image
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)) {
            //  循环遍历
            skuImageList.forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }
        //  sku_attr_value 记录skuId 与 平台属性值的关系！
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {
            //  循环遍历
            skuAttrValueList.forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }
        //  sku_sale_attr_value 记录skuId 与 销售属性值的关系！
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)) {
            //  循环遍历
            skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId()); // 因为前端页面将spuId 传递给了skuInfo
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }
    }

    @Override
    public IPage getSkuInfoPage(Page<SkuInfo> skuInfoPage) {
        //  select * from skuInfo order by id desc limit 0 ,10;
        QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
        skuInfoQueryWrapper.orderByDesc("id");
        return skuInfoMapper.selectPage(skuInfoPage, skuInfoQueryWrapper);
    }

    @Override
    public void onSale(Long skuId) {
        //  商品上架本质： 将sku_info 表中的is_sale = 1;
        //  update sku_info set is_sale = 1 where id = skuId and is_deleted = 0;
        //  你们心中在想： 只改这一个字段，其他的字段是不是都变成 null ;
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);

        //  发送一个消息到队列！
        //  发送消息的内容 根据什么来决定?  根据消费者的需求！
        this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    @Override
    public void cancelSale(Long skuId) {
        //  商品下架本质： 将sku_info 表中的is_sale = 0;
        //  update sku_info set is_sale = 0 where id = skuId and is_deleted = 0;
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);

        //  发送一个消息到队列！
        this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        //  获取最新价格：完美?
        //  select * from sku_info where id = skuId;
        //  优化成 price   select price from sku_info where id = skuId;
        //        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        //        if (skuInfo!=null){
        //            return skuInfo.getPrice();
        //        }
        //  select price from sku_info where id = skuId; 堪称完美 !
        //  声明key
        String lockKey = skuId + ":lock";
        RLock lock = this.redissonClient.getLock(lockKey);
        //  上锁：
        lock.lock();

        try {
            QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
            skuInfoQueryWrapper.select("price").eq("id", skuId);
            SkuInfo skuInfo = skuInfoMapper.selectOne(skuInfoQueryWrapper);
            if (skuInfo != null) {
                return skuInfo.getPrice();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        //  默认返回0
        return new BigDecimal("0");
    }

    @Override
    @GmallCache(prefix = RedisConst.SKUKEY_PREFIX)
    public SkuInfo getSkuInfo(Long skuId) {
        //  获取skuInfo 数据！
        //  skuKey = sku:skuId:info;
        //  return getSkuInfoByRedis(skuId);
        // return getSkuInfoByRedisson(skuId);
        return getSkuInfoDB(skuId);

    }

    private SkuInfo getSkuInfoByRedisson(Long skuId) {
        String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        try {
            //  skuInfo
            SkuInfo skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            if (skuInfo == null) {
                //  缓存中没有数据
                //  上锁！redis  ，redisson！
                //  set key value ex/px timeout nx/xx;
                //  lockKey= sku:skuId:lock
                String lockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
                RLock lock = redissonClient.getLock(lockKey);
                //  获取分布式锁！
                boolean result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //  result=true 表示 获取到锁！
                //  从最终结果来将需要重试么？ 不做重试可以么？
                if (result) {
                    try {
                        //  业务逻辑！
                        skuInfo = getSkuInfoDB(skuId);
                        //  防止一下缓存穿透！
                        if (skuInfo == null) {
                            SkuInfo skuInfo1 = new SkuInfo();
                            //  这个过期时间不应该太长
                            this.redisTemplate.opsForValue().set(skuKey, skuInfo1, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                            return skuInfo1;
                        }
                        //  放入缓存！
                        this.redisTemplate.opsForValue().set(skuKey, skuInfo, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                        return skuInfo;
                    } finally {
                        //  解锁！
                        lock.unlock();
                    }
                } else {
                    Thread.sleep(1000);
                    return getSkuInfo(skuId);
                }
            } else {
                //  缓存中有数据！
                return skuInfo;
            }
        } catch (InterruptedException e) {
            //  报警----> 程序哥哥： 危险..... 写日志.... sendMSG();
            e.printStackTrace();
        }
        //  返回数据库中的数据！  需要停止redis 容器 ！ docker stop CID
        return getSkuInfoDB(skuId);
    }

    /**
     * 提取方法快捷键：ctrl+alt+m
     * 通过redis做分布式锁的方法！
     *
     * @param skuId
     * @return
     */
    private SkuInfo getSkuInfoByRedis(Long skuId) {
        String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        try {
            //  skuInfo
            SkuInfo skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);

            if (skuInfo == null) {
                //  缓存中没有数据
                //  上锁！redis  ，redisson！
                //  set key value ex/px timeout nx/xx;
                //  lockKey= sku:skuId:lock

                String lockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
                String uuid = UUID.randomUUID().toString();
                Boolean result = this.redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
                //  result = true;
                if (result) {
                    //  获取到锁！有权利查询数据库了！ skuId = 124 1000次的时候， 如果是使用uuid 穿透，此方式不能防止！建议使用布隆过滤器！
                    skuInfo = getSkuInfoDB(skuId);
                    //  防止一下缓存穿透！
                    if (skuInfo == null) {
                        SkuInfo skuInfo1 = new SkuInfo();
                        //  这个过期时间不应该太长
                        this.redisTemplate.opsForValue().set(skuKey, skuInfo1, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                        return skuInfo1;
                    }

                    //  放入缓存！
                    this.redisTemplate.opsForValue().set(skuKey, skuInfo, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);

                    //  释放锁资源！ redis + lua 释放！
                    String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";

                    //  执行lua 脚本：
                    //  第一个： 表示 RedisScript 需要执行的lua 脚本 第二个： key 第三个： value
                    DefaultRedisScript defaultRedisScript = new DefaultRedisScript();
                    defaultRedisScript.setScriptText(script);
                    defaultRedisScript.setResultType(Long.class);
                    this.redisTemplate.execute(defaultRedisScript, Arrays.asList("lock"), uuid);

                    return skuInfo;
                } else {
                    //  自旋：先睡一会，再次调用方法！
                    Thread.sleep(100);
                    return getSkuInfo(skuId);
                }
            } else {
                //  缓存中有数据！
                return skuInfo;
            }
        } catch (InterruptedException e) {
            //  报警----> 程序哥哥： 危险..... 写日志.... sendMSG();
            e.printStackTrace();
        }
        //  返回数据库中的数据！  需要停止redis 容器 ！ docker stop CID
        return getSkuInfoDB(skuId);
    }

    private SkuInfo getSkuInfoDB(Long skuId) {
        //  sku_info.id = skuId;
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);

        //  查询skuImage;
        //  select * from sku_image where sku_id = skuId;
        if (skuInfo != null) {
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
            //  赋值商品图片列表数据
            skuInfo.setSkuImageList(skuImageList);
        }

        //  返回数据
        return skuInfo;
    }

    @Override
    @GmallCache(prefix = "CategoryView:")
    public BaseCategoryView getCategoryView(Long category3Id) {
        //  select * from base_category_view where id = category3Id;
        return baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    @GmallCache(prefix = "SpuSaleAttrListCheck:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        //  获取数据，实现多表关联查询！  分布式锁业务逻辑！

        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId, spuId);
    }

    @Override
    @GmallCache(prefix = "SkuValueIdsMap:")
    public Map getSkuValueIdsMap(Long spuId) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        //  获取到数据库中对应的数据！
        //        value_ids sku_id
        //        3729|3731	21 ---- map
        //        3729|3730	22 ---- map
        List<Map> mapList = skuSaleAttrValueMapper.selectSkuValueIdsMap(spuId);
        //  循环遍历这个集合数据
        if (!CollectionUtils.isEmpty(mapList)) {
            mapList.forEach(map -> {
                hashMap.put(map.get("value_ids"), map.get("sku_id"));
            });
            //  拉姆达表达式！
            //            Stream<Object> objectStream = mapList.stream().map(map -> {
            //                String valueIds = (String) map.get("value_ids");
            //                String skuId = (String) map.get("sku_id");
            //                HashMap<Object, Object> hashMap = new HashMap<>();
            //                return hashMap.put(valueIds, skuId);
            //            });
        }
        return hashMap;
    }

    @Override
    @GmallCache(prefix = "SpuPoster:")
    public List<SpuPoster> findSpuPosterBySpuId(Long spuId) {
        return spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id", spuId));
    }

    @Override
    @GmallCache(prefix = "AttrList:")
    public List<BaseAttrInfo> getAttrList(Long skuId) {

        //  获取数据
        List<BaseAttrInfo> baseAttrInfoList = baseAttrInfoMapper.selectAttrList(skuId);
        return baseAttrInfoList;
    }

    @Override
    @GmallCache(prefix = "CategoryList:")
    public List<JSONObject> getCategoryList() {
        //  获取到所有分类数据！
        List<JSONObject> list = new ArrayList<>();
        //  分类名称 + 分类Id 在 base_category_view 视图中！
        List<BaseCategoryView> categoryViewList = baseCategoryViewMapper.selectList(null);
        //  获取一级分类数据 ，以一级分类category1_id 分组，
        //  map key = category1_id value = List<BaseCategoryView>
        //  categoryViewList.stream().map(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //  category1_id = 1  category1_id = 2
        //  70 --> 20 明白;
        Map<Long, List<BaseCategoryView>> listMap = categoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));

        //  声明一个变量index
        int index = 1;
        //  遍历集合
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = listMap.entrySet().iterator();
        while (iterator.hasNext()) {
            //  创建一个 JSONObject 对象
            JSONObject category1 = new JSONObject();
            Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
            Long category1Id = entry.getKey();
            List<BaseCategoryView> categoryViewList1 = entry.getValue();

            //  5个人;
            category1.put("index", index);

            category1.put("categoryName", categoryViewList1.get(0).getCategory1Name());
            category1.put("categoryId", category1Id);

            //  变量自增
            index++;

            //  以二级分类Id 分组
            Map<Long, List<BaseCategoryView>> listMap2 = categoryViewList1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            //  声明一个集合来存储二级分类数据
            List<JSONObject> category2ChildList = new ArrayList<>();
            //  循环遍历
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = listMap2.entrySet().iterator();
            while (iterator1.hasNext()) {
                //  创建一个 JSONObject 对象
                JSONObject category2 = new JSONObject();
                Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
                Long category2Id = entry1.getKey();
                List<BaseCategoryView> categoryViewList2 = entry1.getValue();

                category2.put("categoryId", category2Id);
                category2.put("categoryName", categoryViewList2.get(0).getCategory2Name());

                category2ChildList.add(category2);

                //  获取三级分类数据！
//                categoryViewList2.forEach();
                //  声明一个集合来存储三级分类数据
//                List<JSONObject> category3ChildList = new ArrayList<>();
//                for (BaseCategoryView baseCategoryView : categoryViewList2) {
//                    JSONObject category3 = new JSONObject();
//                    category3.put("categoryId", baseCategoryView.getCategory3Id());
//                    category3.put("categoryName", baseCategoryView.getCategory3Name());
//                    category3ChildList.add(category3);
//                }
                //  拉姆达表达式！
                List<JSONObject> category3ChildList = categoryViewList2.stream().map(baseCategoryView -> {
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId", baseCategoryView.getCategory3Id());
                    category3.put("categoryName", baseCategoryView.getCategory3Name());
                    return category3;
                }).collect(Collectors.toList());

                //  将三级分类数据集合放入二级分类数据
                category2.put("categoryChild", category3ChildList);
            }
            //  将二级分类数据集合放入一级分类数据
            category1.put("categoryChild",category2ChildList);
            //  将一级分类数放入list 集合
            //  ${list}
            list.add(category1);
        }
        //  返回数据！
        return list;
    }

    @Override
    public BaseTrademark getTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }

}
